import { useState, useEffect } from 'react';
import { Button, Text, Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose } from 'packages/ui-shared/src/atoms';
import { useSession } from '../hooks/useSession';

export default function SessionIndicator() {
  const { session, isAuthenticated, logout, extendSession, getSessionStats } = useSession();
  const [showSessionDialog, setShowSessionDialog] = useState(false);
  const [timeRemaining, setTimeRemaining] = useState<string>('');

  // 更新剩余时间显示
  useEffect(() => {
    if (session && isAuthenticated) {
      const updateTimeRemaining = () => {
        const stats = getSessionStats();
        setTimeRemaining(stats.timeRemaining || '已过期');
      };

      updateTimeRemaining();
      const interval = setInterval(updateTimeRemaining, 1000); // 每秒更新

      return () => clearInterval(interval);
    }
    return undefined;
  }, [session, isAuthenticated, getSessionStats]);

  if (!isAuthenticated || !session) {
    return null;
  }

  const handleLogout = async () => {
    await logout();
    setShowSessionDialog(false);
  };

  const handleExtendSession = async () => {
    const success = await extendSession();
    if (success) {
      setShowSessionDialog(false);
    }
  };

  return (
    <>
      {/* 会话状态指示器 */}
      <div className="fixed top-4 right-4 z-50">
        <div className="bg-white border border-gray-200 rounded-lg shadow-lg p-3 min-w-[200px]">
          <div className="flex items-center justify-between">
            <div className="flex-1">
              <Text className="text-sm font-medium text-gray-900">
                {session.userName}
              </Text>
              <Text className="text-xs text-gray-500">
                {session.userRole} • {timeRemaining}
              </Text>
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setShowSessionDialog(true)}
              className="ml-2 text-xs"
            >
              详情
            </Button>
          </div>
          
          {/* 会话状态条 */}
          <div className="mt-2">
            <div className="w-full bg-gray-200 rounded-full h-1.5">
              <div 
                className={`h-1.5 rounded-full transition-all duration-1000 ${
                  timeRemaining.includes('已过期') 
                    ? 'bg-red-500' 
                    : timeRemaining.includes('分') && parseInt(timeRemaining) < 5
                    ? 'bg-yellow-500'
                    : 'bg-green-500'
                }`}
                style={{ 
                  width: timeRemaining.includes('已过期') 
                    ? '0%' 
                    : timeRemaining.includes('分') 
                    ? `${Math.max(0, (parseInt(timeRemaining) / 30) * 100)}%`
                    : '100%'
                }}
              />
            </div>
          </div>
        </div>
      </div>

      {/* 会话详情对话框 */}
      <Dialog open={showSessionDialog} onOpenChange={setShowSessionDialog}>
        <DialogContent size="md">
          <DialogHeader>
            <DialogTitle>会话管理</DialogTitle>
            <DialogDescription>管理您的当前会话</DialogDescription>
          </DialogHeader>

          <div className="py-4 space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Text className="text-sm font-medium text-gray-700">用户名</Text>
                <Text className="text-sm text-gray-900">{session.userName}</Text>
              </div>
              <div>
                <Text className="text-sm font-medium text-gray-700">角色</Text>
                <Text className="text-sm text-gray-900">{session.userRole}</Text>
              </div>
              <div>
                <Text className="text-sm font-medium text-gray-700">登录时间</Text>
                <Text className="text-sm text-gray-900">
                  {new Date(session.loginTime).toLocaleString('zh-CN')}
                </Text>
              </div>
              <div>
                <Text className="text-sm font-medium text-gray-700">最后活动</Text>
                <Text className="text-sm text-gray-900">
                  {new Date(session.lastActivity).toLocaleString('zh-CN')}
                </Text>
              </div>
              <div>
                <Text className="text-sm font-medium text-gray-700">IP地址</Text>
                <Text className="text-sm text-gray-900">{session.ipAddress}</Text>
              </div>
              <div>
                <Text className="text-sm font-medium text-gray-700">MFA状态</Text>
                <Text className="text-sm text-gray-900">
                  {session.mfaVerified ? '已验证' : '未验证'}
                </Text>
              </div>
            </div>

            <div className="pt-4 border-t">
              <div className="flex space-x-2">
                <Button
                  variant="outline"
                  onClick={handleExtendSession}
                  className="flex-1"
                >
                  延长会话
                </Button>
                <Button
                  variant="outline"
                  onClick={handleLogout}
                  className="flex-1 text-red-600 hover:text-red-800"
                >
                  安全登出
                </Button>
              </div>
            </div>
          </div>

          <DialogFooter>
            <DialogClose>关闭</DialogClose>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
